import sdk from '../index';
import { ApiCall } from "tsrpc";
import player from "../rpg/entity/player";
import { ClientAction, ClientInfo, Message } from "../../shared/api_bot/IMassage";
import { ComType } from "./component";
import intent_component from "../../component/intent_component";
import { ReqMessage, ResMessage } from "../../shared/api_bot/PtlMessage";
import { mathType } from "./face";
import { BaseBody } from "../rpg/entity/body_base";
import { wordMap } from "../rpg/wordMap";
import SceneManager from '../manage/SceneManager';
import pos_component from '../../component/pos_component';
import { PositionService } from '../../service/PositionService';
import { TaskService } from '../../service/TaskService';
import { TaskStatus } from '../rpg/types/task';
import DungeonManager from '../manage/DungeonManager';


// 添加类型定义
export interface IntentHandler {
    mathType: mathType;
    mathStr: string;
    action: Function;
    updateTime: number;
    isHideMath: boolean;
    self: any;
}
export interface analysisIntent {
    message: string;
    player: player;
    Message: Message;
    call: ApiCall<ReqMessage, ResMessage>;
    ClientInfo: ClientInfo;
}

// 地图指令配置接口
export interface MapIntentConfig {
    command: string;
    action: string;
    mathType: mathType;
    isHideMath?: boolean;
    description?: string;
}

export class baseScene {
    map: wordMap = new wordMap();
    scene: string = 'none';
    sceneManager = SceneManager;
    private intentHandlers: IntentHandler[] = [];  // 添加意图处理器存储
    private mapIntentHandlers: IntentHandler[] = [];  // 地图专用意图处理器

    constructor() {
        // 各地图可以根据需要注册任务指令
    }
    
    // 默认的任务栏方法 - 只显示世界任务
    async taskbar(data: analysisIntent) {
        const tasks = await TaskService.getPlayerTasks(data.player);
        if (tasks.world && tasks.world.length > 0) {
            this.showWorldTasks(data.player, tasks.world);
        } else {
            data.player.client_text('🌍 当前地图暂无世界任务');
        }
    }
    
    /**
     * 显示世界任务列表
     * @param player 玩家对象
     * @param worldTasks 世界任务列表
     */
    protected async showWorldTasks(player: any, worldTasks: any[]) {
        let card = sdk.tool.card.create();
        card.title('🌍 世界任务');
        
        if (worldTasks.length === 0) {
            card.l('当前地图暂无世界任务');
        } else {
            // 添加世界任务描述
            card.l('🌌 主城的大门紧闭，唯有完成世界任务才能获得回归的资格');
            card.l('💎 完成任务的勇者将获得丰厚的奖励，这是对强者的认可');
            
            // 检查是否有已完成的世界任务
            const completedTasks = worldTasks.filter(task => 
                task.targets.every((target: any) => target.current >= target.count)
            );
            
            if (completedTasks.length > 0) {
                card.l('🎉 世界任务已完成！结算后将发放奖励并传送回主城');
            }
            
            card.l('');
            
            worldTasks.forEach((task, index) => {
                // 显示任务目标，每个目标前面加emoji
                task.targets.forEach((target: any, targetIndex: number) => {
                    const progress = Math.min(target.current, target.count);
                    const statusEmoji = target.current >= target.count ? '✅' : '🔄';
                    card.l(`${statusEmoji}${target.description}(${progress}/${target.count})`);
                });
                
                // 显示任务奖励
                if (task.rewards && task.rewards.length > 0) {
                    card.l('┄━═🎁任务奖励═━┄');
                    task.rewards.forEach((reward: any, rewardIndex: number) => {
                        card.l(`🎁${reward.name} x${reward.count}`);
                    });
                }
            });
            
            // 如果有已完成的任务，添加结算按钮
            if (completedTasks.length > 0) {
                this.registerButtonIntents(card, [
                    { text: '结算', action: 'handleSettleWorldTasks', mathType: mathType.完全匹配 }
                ]);
            }
        }
        
        player.client_text(card.getText());
    }
    // 处理世界任务结算
    async handleSettleWorldTasks(data: analysisIntent) {
        const result = await TaskService.settleWorldTasks(data.player);
        
        if (result.success) {
            let card = sdk.tool.card.create();
            card.title('🎉世界任务结算成功!');
            card.l(result.message);
            
            if (result.rewards && result.rewards.length > 0) {
                card.l('┄━═🎁获得奖励═━┄');
                result.rewards.forEach((reward: any) => {
                    card.l(`🎁${reward.name} x${reward.count}`);
                });
            }
            
            data.player.client_text(card.getText());
        } else {
            data.player.client_text(`❌结算失败: ${result.message}`);
        }
    }
    getWebUrl(): string {
        return 'https://dew-bot.cn/test/client/';
    }
    tips_webUrl(data: analysisIntent) {
        data.player.client_text('请前往:' + this.getWebUrl());
    }
    // 新增注册意图
    registerIntent(mathType: mathType, mathStr: string, isHideMath: boolean, action: Function, self: any = this) {
        this.intentHandlers.push({ mathType, mathStr, isHideMath, action, self, updateTime: Date.now() });
        this.intentHandlers.sort((a, b) => {
            if (a.mathType === b.mathType) {
                return b.mathStr.length - a.mathStr.length;
            }
            return a.mathType - b.mathType;
        });
    }

    // 注册地图专用意图
    registerMapIntent(mathType: mathType, mathStr: string, isHideMath: boolean, action: Function, self: any = this) {
        // 检查是否已存在相同的意图，如果存在则移除旧的
        const existingIndex = this.mapIntentHandlers.findIndex(handler => 
            handler.mathStr === mathStr && handler.mathType === mathType
        );
        
        if (existingIndex !== -1) {
            // 移除旧的意图处理器
            this.mapIntentHandlers.splice(existingIndex, 1);
        }
        
        // 添加新的意图处理器
        this.mapIntentHandlers.push({ mathType, mathStr, isHideMath, action, self, updateTime: Date.now() });
        this.mapIntentHandlers.sort((a, b) => {
            if (a.mathType === b.mathType) {
                return b.mathStr.length - a.mathStr.length;
            }
            return a.mathType - b.mathType;
        });
    }

    // 批量注册地图意图
    registerMapIntents(configs: MapIntentConfig[]) {
        configs.forEach(config => {
            this.registerMapIntent(
                config.mathType,
                config.command,
                config.isHideMath || true,
                (this as any)[config.action],
                this
            );
        });
    }

    // 注册按钮意图
    registerButtonIntents(card: any, configs: Array<{
        text: string;
        action: string;
        mathType: mathType;
        isHideMath?: boolean;
    }>) {
        configs.forEach(config => {
            card.button(config.text, () => {
                // 当按钮被点击时，注册对应的意图
                this.registerMapIntent(
                    config.mathType,
                    config.text,
                    config.isHideMath || false,
                    (this as any)[config.action],
                    this
                );
            });
        });
    }


    // 消息意图分析
    analysisIntent(data: analysisIntent) {

        // intentHandlers 排序
        /**
         * 排序规则
         * 1 完全匹配 优先级最高
         * 2 开头匹配 优先级次之
         * 3 模糊匹配 优先级最低
         * 准时以上规则的同时还要按字符串长度排序
         */
        let com_pop = (data.player.getComponent(ComType.对话框) as any);
        if (com_pop.haveShow()) {
            this._analysisIntent(data, com_pop.getIntentHandlers())
            return;
        }
        let com_intentHandlers = (data.player.getComponent(ComType.意图) as intent_component);
        let com_list = com_intentHandlers.getIntentHandlers();

        // 合并所有意图处理器并去重，以最后一次注册的为准
        let matchList = this.mergeAndDeduplicateIntents([...com_list,...this.intentHandlers,...this.mapIntentHandlers ]);
        this._analysisIntent(data, matchList)

    }
    private _analysisIntent(data: analysisIntent, matchList: IntentHandler[]) {
        let msg = data.message.trim();
        let handled = false;

        for (const handler of matchList) {
            switch (handler.mathType) {
                case mathType.全部拦截:
                    handler.action.call(handler.self, data);
                    handled = true;
                    break;
                case mathType.完全匹配:
                    if (msg === handler.mathStr) {
                        handler.action.call(handler.self, data);
                        handled = true;
                    }
                    break;

                case mathType.开头匹配:
                    if (msg.startsWith(handler.mathStr)) {
                        const remaining = msg.slice(handler.mathStr.length).trim();
                        data.message = remaining;
                        handler.action.call(handler.self, data);
                        handled = true;
                    }
                    break;
                case mathType.模糊匹配:
                    if (msg.includes(handler.mathStr)) {
                        handler.action.call(handler.self, data);
                        handled = true;
                    }
                    break;
            }

            if (handled) return; // 匹配到立即返回

        }

        if (!handled) {
            // 未命中处理逻辑
            this.miss(msg, data, matchList);
        }
    }
    async tick(data: analysisIntent) {

    }

    // 获取地图意图处理器列表（用于调试）
    getMapIntentHandlers(): IntentHandler[] {
        return this.mapIntentHandlers;
    }

    // 清除地图意图处理器
    clearMapIntents() {
        this.mapIntentHandlers = [];
    }

    // 合并并去重意图处理器，以updateTime更大的为准
    private mergeAndDeduplicateIntents(intentHandlers: IntentHandler[]): IntentHandler[] {
        const intentMap = new Map<string, IntentHandler>();
        
        // 遍历所有意图处理器，如果key相同，保留updateTime更大的
        intentHandlers.forEach(handler => {
            const key = `${handler.mathType}_${handler.mathStr}`;
            const existing = intentMap.get(key);
            
            if (!existing || handler.updateTime > existing.updateTime) {
                intentMap.set(key, handler);
            }
        });
        
        // 转换回数组并排序
        const deduplicatedIntents = Array.from(intentMap.values());
        deduplicatedIntents.sort((a, b) => {
            if (a.mathType === b.mathType) {
                return b.mathStr.length - a.mathStr.length;
            }
            return a.mathType - b.mathType;
        });
        
        return deduplicatedIntents;
    }

    // 通用位置处理方法
    onPosition(data: analysisIntent) {
        data.player.client_text('地图未开发');
    }
    /**
     * 回城
     * @param data 
     */
    async onBackHome(data: analysisIntent) {
        let com_post = data.player.getComponent(ComType.位置) as pos_component;
        let scene = sdk.scene.getScene(com_post.sceneName);
        if (!scene) {
            return;
        }
        
        // 检查世界任务是否完成
        const worldTasksCompleted = await this.checkWorldTasksCompleted(data.player);
        if (!worldTasksCompleted) {
            // 获取未完成的世界任务信息
            const tasks = await TaskService.getPlayerTasks(data.player);
            let card = sdk.tool.card.create();
            card.title('⚠️ 无法回城');
            card.l('世界任务尚未完成，无法安全回到主城！');
            card.l('');
            card.l('请完成所有世界任务后再尝试回城。');
            data.player.client_text(card.getText());
            return;
        }
        
        // 世界任务完成，允许回城
        scene.switchMap(data.player.getMaster(), 'default');
    }

    // 切换地图
    async switchMap(player: BaseBody, newSceneName: string, difficulty?: string) {
        // 获取玩家的位置组件
        const com_pos = player.getComponent(ComType.位置) as any;
        if (com_pos) {
            const oldSceneName = com_pos.sceneName;
            
            // 清理旧地图的世界任务
            if (oldSceneName && oldSceneName !== 'default' && oldSceneName !== '主城') {
                try {
                    await sdk.worldTask.clearPlayerWorldTasks(player.id);
                } catch (error) {
                    console.error('清理旧地图世界任务失败:', error);
                }
            }
            
            // 清除旧地图的引用
            if (com_pos._cell) {
                com_pos._cell.leave(player);
                com_pos._cell = undefined;
            }
            com_pos._map = undefined;
            
            // 更新场景名称
            com_pos.sceneName = newSceneName;

            // 获取新场景
            const newScene = sdk.scene.getScene(newSceneName);
            if (newScene) {
                // 如果指定了难度，设置地图难度
                if (difficulty) {
                    newScene.map.difficulty = difficulty;
                }
                
                // 如果切换到主城（default场景），设置玩家坐标为(0,0)
                if (newSceneName === 'default') {
                    // 创建或获取(0,0)坐标的单元格
                    const homeCell = newScene.map.cellMap.get('0_0');
                    if (homeCell) {
                        com_pos._cell = homeCell;
                        homeCell.join(player);
                    } else {
                        // 如果(0,0)单元格不存在，创建一个
                        const { wordCell } = require('../rpg/wordMap');
                        const newHomeCell = new wordCell('0_0');
                        newScene.map.cellMap.set('0_0', newHomeCell);
                        com_pos._cell = newHomeCell;
                        newHomeCell.join(player);
                    }
                }
                
                // 为新地图生成世界任务
                if (newSceneName !== 'default') {
                    try {
                        const worldTasks = await sdk.worldTask.generateWorldTasks(newSceneName, player.id);
                        if (worldTasks.length > 0) {
                            player.client_text(`🌍 已切换到地图: ${newScene.map.name} (${newScene.map.difficulty})\n🌍 生成了 ${worldTasks.length} 个世界任务`);
                        } else {
                            player.client_text(`🌍 已切换到地图: ${newScene.map.name} (${newScene.map.difficulty})`);
                        }
                    } catch (error) {
                        console.error('生成世界任务失败:', error);
                        player.client_text(`🌍 已切换到地图: ${newScene.map.name} (${newScene.map.difficulty})`);
                    }
                } else {
                    player.client_text(`🌍 已切换到地图: ${newScene.map.name}`);
                }
                return true;
            } else {
                player.client_text(`❌ 地图 ${newSceneName} 不存在`);
                return false;
            }
        } else {
            player.client_text('❌ 无法获取位置组件');
            return false;
        }
    }

    // 移动提示
    handleMove(data: analysisIntent) {
        data.player.client_text('💡移动指令: 上 下 左 右');
    }

    // 上
    handleMoveUp(data: analysisIntent) {
        const result = PositionService.moveToDirection(this.map, data.player, '上');
        if (!result.success) {
            data.player.client_text(result.message);
            return;
        }
        this.onPosition(data);
    }

    // 下
    handleMoveDown(data: analysisIntent) {
        const result = PositionService.moveToDirection(this.map, data.player, '下');
        if (!result.success) {
            data.player.client_text(result.message);
            return;
        }
        this.onPosition(data);
    }

    // 左
    handleMoveLeft(data: analysisIntent) {
        const result = PositionService.moveToDirection(this.map, data.player, '左');
        if (!result.success) {
            data.player.client_text(result.message);
            return;
        }
        this.onPosition(data);
    }

    // 右
    handleMoveRight(data: analysisIntent) {
        const result = PositionService.moveToDirection(this.map, data.player, '右');
        if (!result.success) {
            data.player.client_text(result.message);
            return;
        }
        this.onPosition(data);
    }

    // 探索
    handleExplore(data: analysisIntent) {
        const result = PositionService.exploreCurrentPosition(this.map, data.player);
        if (!result.success) {
            data.player.client_text(result.message);
            return;
        }
        this.onPosition(data);
    }

    // 侦察
    handleSpy(data: analysisIntent) {
        const cell = this.map.checkPos(data.player);
        const index_data = sdk.tool.common.cover_number(data.Message.content);
        if (!index_data.k1) {
            data.player.client_text('侦察ID不能为空');
            return;
        }
        const spyResult = PositionService.spyTarget(cell, index_data.k1);
        if (!spyResult.success) {
            data.player.client_text(spyResult.message);
            return;
        }
        const target = spyResult.target!;
        const rpgCom = target.getComponent(ComType.rpg) as any;
        rpgCom.client_lookAtt(data, '侦察');
    }

    // 捕捉
    handleCapture(data: analysisIntent) {
        const cell = this.map.checkPos(data.player);
        const index_data = sdk.tool.common.cover_number(data.Message.content);
        if (!index_data.k1) {
            data.player.client_text('捕捉ID不能为空');
            return;
        }
        const bagCom = data.player.getComponent(ComType.背包) as any;
        const captureResult = PositionService.captureTarget(
            cell,
            index_data.k1,
            [] // 实际验证在order_confirm中进行
        );
        if (!captureResult.success) {
            data.player.client_text(captureResult.message);
            return;
        }
        const bagOrderResult = bagCom.order_confirm(captureResult.requiredItems!);
        if (bagOrderResult) {
            bagCom.addItem(captureResult.capturedItem!);
            data.player.client_text(captureResult.message);
        } else {
            data.player.client_text('捕捉失败!');
        }
    }

    /**
   * 字符串相识度算法
   * @param x 
   * @param y 
   * @returns 
   */
    private xsd(x: any, y: any) {
        if (x === y) return 1;
        if (x.length === 0 || y.length === 0) return 0;

        const matrix = [];
        for (let i = 0; i <= x.length; i++) {
            matrix[i] = [i];
        }
        for (let j = 0; j <= y.length; j++) {
            matrix[0][j] = j;
        }

        for (let i = 1; i <= x.length; i++) {
            for (let j = 1; j <= y.length; j++) {
                if (x[i - 1] === y[j - 1]) {
                    matrix[i][j] = matrix[i - 1][j - 1];
                } else {
                    matrix[i][j] = Math.min(
                        matrix[i - 1][j] + 1,
                        matrix[i][j - 1] + 1,
                        matrix[i - 1][j - 1] + 1
                    );
                }
            }
        }

        const maxLength = Math.max(x.length, y.length);
        return 1 - matrix[x.length][y.length] / maxLength;
    }
    miss(msg: string, data: analysisIntent, list: IntentHandler[]) {

        // bot.sendText(data.tolocation,str || '错误的内容');
        let matchList = list;
        matchList = matchList.filter((item) => {
            return !item.isHideMath
        })
        matchList.sort((A, B) => {
            return this.xsd(msg, B.mathStr) - this.xsd(msg, A.mathStr);
        });
        
        // 检查是否有相似度大于0的匹配项
        const highSimilarityMatches = matchList.filter(item => this.xsd(msg, item.mathStr) > 0);
        
        // 如果只有一个相似度大于0的匹配项，直接调用
        if (highSimilarityMatches.length === 1) {
            const bestMatch = highSimilarityMatches[0];
            bestMatch.action.call(bestMatch.self, data);
            return;
        }
        
        if (matchList.length > 0) {
            if (this.xsd(msg, matchList[0].mathStr) == 0) {
                let arr = matchList
                arr.sort(() => {
                    return Math.random() - 0.5
                })

            }
        }

        let temp = `╭°❀•°你想找什么•❀╮\n`;
        for (let index = 0; index < 15; index++) {
            let item = matchList[index];
            if (!item) {
                break;
            }
            // let from = item.self.clsName ? `(来自${item.self.clsName})` : '';
            if (this.xsd(msg, item.mathStr) > 0) {
                temp += `⭐[${item.mathStr}]⭐`;
            } else {
                temp += `@bot ${item.mathStr}`;
            }

            temp += `\n`
        }
        temp += `💡这是tips消息，还未填充内容`;
        data.player.client_text(temp);
    }

    /**
     * 检查世界任务是否完成
     * @param player 玩家对象
     * @returns 是否所有世界任务都已完成
     */
    protected async checkWorldTasksCompleted(player: any): Promise<boolean> {
        try {
            const tasks = await TaskService.getPlayerTasks(player);
            if (tasks.world.length === 0) {
                return true; // 没有世界任务也算完成
            }
            
            // 检查所有世界任务是否都完成
            for (const task of tasks.world) {
                for (const target of task.targets) {
                    if (target.current < target.count) {
                        return false; // 有未完成的目标
                    }
                }
            }
            return true; // 所有目标都完成
        } catch (error) {
            console.error('检查世界任务完成状态失败:', error);
            return false;
        }
    }
}

